package org.linlinjava.litemall.wx.service;


import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.constant.ReturnValue;

import org.linlinjava.litemall.core.mapper.SysPlatformCutpriceHistoryMap;
import org.linlinjava.litemall.core.task.TaskService;
import org.linlinjava.litemall.core.util.*;
import org.linlinjava.litemall.core.vo.Lock;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.po.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.APIUtil;
import org.linlinjava.litemall.wx.util.*;
import org.linlinjava.litemall.wx.vo.wechart.CreateQr;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


import javax.annotation.Resource;
import java.io.InputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.concurrent.TimeUnit;



@Service
public class WxRedPacaketsService {
    private final Log logger = LogFactory.getLog(WxRedPacaketsService.class);

    @Autowired
    private LitemallUserService userService;
    @Autowired
    private LitemallRedPacaketsService redPacaketsService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private SystemWxConfigService systemWxConfigService;
    @Autowired
    private LitemallRedPacaketsHistoryService litemallRedPacaketsHistoryService;
    @Autowired
    private RedisUntil redisService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private LitemallUserService litemallUserService;
    @Autowired
    private ReceiveRecordService receiveRecordService;
    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private ArticlesService articlesService;
    @Autowired
    private DistributedLockHandler distributedLockHandler;
    @Autowired
    private WxService wxService;
    @Autowired
    private WxGiveRedPackService wxGiveRedPackService;
    @Autowired
    private UserCutPriceService userCutPriceService;
    @Autowired
    private RestTemplate restTemplate;


    private String message;
    private String enterprisePaymentMessage;

    public String getEnterprisePaymentMessage() {
        return enterprisePaymentMessage;
    }

    public void setEnterprisePaymentMessage(String enterprisePaymentMessage) {
        this.enterprisePaymentMessage = enterprisePaymentMessage;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }


    public int friendsBargainPlatformCutprice(String userId, Long userCutpriceId, String formId,String appletName) throws Exception {
       // logger.info("打印参数： userCutpriceId：" + userCutpriceId + "，userId：" + userId + "，formId：" + formId);
        int flag = 0;
        LitemallRedPacaketsHistory spfc = litemallRedPacaketsHistoryService.getCutRedpacaketById(userCutpriceId);
        SysWxConfig wxConfig = systemWxConfigService.getconfigByAppletNam(appletName);
        if (spfc != null) {
            LitemallRedPacakets platformCutprice = redPacaketsService.findById(spfc.getCutpriceId());
            if (platformCutprice == null) {
                this.setMessage("活动不存在");
                return flag;
            }
            if (platformCutprice.getCutpriceMode() == 4 || platformCutprice.getCutpriceMode() == 5)
                redisService.set("formId_UIL_" + userCutpriceId + "_" + userId, formId, spfc.getDuration() + 10);
            flag = this.auctionBargain(spfc, platformCutprice, userCutpriceId, userId,wxConfig);

        } else {
            logger.error("参数异常 userCutpriceId: " + userCutpriceId + " ，userId" + userId);
        }
        return flag;
    }

    /**
     * @Description: generateQr
     * @param: [userItemListId]
     * @return: org.springframework.http.ResponseEntity<?>
     * @auther: caiy
     * @date: 2019/7/11 0011 15:52
     */

    public ResponseEntity<?> generateQr(Long userItemListId,String appletname) throws Exception {
        LitemallRedPacaketsHistory spf =  litemallRedPacaketsHistoryService.getCutRedpacaketById(userItemListId);
        SysWxConfig wxConfig = systemWxConfigService.getconfigByAppletNam(appletname);
        String actoken = wxService.getAccess_token(wxConfig.getWxSubappid(),wxConfig.getWxSubappsecret());
        //String url = "https://api.weixin.qq.com/wxa/getwxacode?access_token="
        String url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token="
                + actoken;
        logger.info("url is : " + url);
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(type);
        headers.add("Accept", MediaType.IMAGE_JPEG.toString());
        InputStream inputStream = null;
        try {
            CreateQr qrParam = new CreateQr();
            qrParam.setPath("/pages/index/index?cutpriceId=" + spf.getId() + "&share=true&scene=1007");
            qrParam.setWidth(430);
            HttpEntity<String> formEntity = new HttpEntity<String>(JsonParser.toJson(qrParam),
                    headers);
            ResponseEntity<byte[]> responseEntity = restTemplate.exchange(url, HttpMethod.POST,
                    formEntity, byte[].class);
            logger.info(responseEntity.getHeaders());
            logger.info("-----------------------");
            logger.info(responseEntity.getBody());
            if (200 == responseEntity.getStatusCodeValue()) {
                byte[] result = responseEntity.getBody();
                //String imgUrl = QiniuUtil.upload(result);
                String img = UUIDHexGenerator.generate();
                String path = GlobalValue.imagePathPrefix + img + ".png";
                String pathW = GlobalValue.imagePathPrefixW + img + ".png";
                logger.info("path:" + path + ",pathW:" + pathW);
       /* BASE64Encoder encoder = new BASE64Encoder();
        String binary = encoder.encodeBuffer(result).trim();*/
                UploadUtils.byte2image(result, pathW);
                return new ResponseEntity<>(new ReturnValue(ReturnValue.success, path), HttpStatus.OK);
            } else {
                logger.error("get qr error!!!");
                logger.error(responseEntity.getStatusCodeValue());
                logger.error(responseEntity.getBody());
            }
            Thread.sleep(500);
        } catch (Exception e) {
            logger.error("get qr error!!!" + e.getMessage(), e);
            generateQr(userItemListId,appletname);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
        return new ResponseEntity<>(new ReturnValue(ReturnValue.fail, "生成失败"), HttpStatus.OK);
    }

    /**
     * 企业付款到零钱发放红包
     **/

    public ResponseEntity<?> enterprisePayment(Long userItemListId, String subAppId, String userId) {
        try {
            logger.info("userItemListId:" + userItemListId + "subAppId" + subAppId + "userId:" + userId);
            int price = 0;
            //subAppId = "612805f0bd1b5fb6953cba666ec0153a";
            LitemallRedPacaketsHistory sph = litemallRedPacaketsHistoryService.getCutRedpacaketById(userItemListId);

            int flag = 0;
            if (sph.getCutpriceMode() == 3) {
                flag = userCutPriceService.enterprisePayment(sph, subAppId);
                price = sph.getPrice();
            } else if (sph.getCutpriceMode() > 3) {
                if (sph.getCutpriceMode() == 5) {
                    String message = "";
                    ReceiveRecord receiveRecord = wxGiveRedPackService.receivingSpeedRace(userId, sph);
                    message = redPacaketsService.getEnterprisePaymentMessage();
                    logger.info("flag:" + flag + "message:" + message);
                    if (receiveRecord == null && StringUtils.isNotBlank(message)) {
                        return new ResponseEntity<Object>(new ReturnValue(ReturnValue.fail, message), HttpStatus.OK);
                    }
                    if (receiveRecord != null && receiveRecord.getId() != null) {
                        Map<String, Integer> map = userCutPriceService.enterprisePaymentSpecial(sph, subAppId, userId);
                        flag = map.get("flag");
                        price = map.get("price");
                        logger.info(map);
                    }

                } else if (sph.getCutpriceMode() == 4) {
                    Map<String, Integer> map = userCutPriceService.enterprisePaymentSpecial(sph, subAppId, userId);
                    flag = map.get("flag");
                    price = map.get("price");
                    logger.info(map);
                }
            } else {
                logger.error("receivingSpeedRace出错");
            }
            if (flag == 1) {
                return new ResponseEntity<>(new ReturnValue(ReturnValue.success, price), HttpStatus.OK);
            } else if (flag == 2) {
                return new ResponseEntity<Object>(new ReturnValue(ReturnValue.fail, "任务尚未完成"), HttpStatus.OK);
            } else if (flag == 3) {
                return new ResponseEntity<Object>(new ReturnValue(ReturnValue.fail, "你已领过同类红包，不可贪心哦"), HttpStatus.OK);
            } else if (flag == 4) {
                return new ResponseEntity<Object>(new ReturnValue(ReturnValue.fail, "红包过期未领已失效"), HttpStatus.OK);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity<Object>(new ReturnValue(ReturnValue.fail, "领取次数达到今日上线或不能重复领取"), HttpStatus.OK);
    }

    /**
     * 发平台优惠券
     */
    public int giveCoupon(Long userItemListId, String appletName) throws Exception {
        if (appletName == null || appletName == "") {
            logger.error("appletname不可为空");
            return 0;
        }
        return wxGiveRedPackService.giveCoupon(userItemListId, appletName);
    }

    /**
     * 根据用户userId查询此用户发起的盘红包活动
     **/
    public List<LookCutpricePo> findCutpriceByUserIdNew(String userId) throws Exception {
        List<LookCutpricePo> lookCutpricePos = new ArrayList<>();
        // lookCutpricePos = sysPlatformCutpriceHistoryCostom.getLookCutpricePoList(userId, flag);
        if (userId == null) {
            logger.error("用户UserId为空");
            return null;
        }
        List<LitemallRedPacaketsHistory> listHistory = litemallRedPacaketsHistoryService.findRedPacaketsListByUserId(userId);
        if (listHistory != null) {
            LookCutpricePo lookpo = null;
            LitemallRedPacakets pacakets = null;
            Long createtime;
            for (LitemallRedPacaketsHistory history : listHistory) {
                pacakets = null;
                createtime = null;
                lookpo = new LookCutpricePo();
                //判断此红包是否过期
                createtime = history.getCreateTime().toInstant(ZoneOffset.of("+8")).toEpochMilli() / 1000;
                createtime += history.getDuration();
                //活动未失效或者红包已经领取的或者成功的红包
                if (LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli() / 1000 < createtime || history.getStatus() == 0 || history.getStatus() == 1) {
                    lookpo.setPlatformCutpriceHistoryId(history.getId());
                    lookpo.setOwner(1);
                    lookpo.setTotalReducation(history.getTotalReducation());
                    lookpo.setNeedCutvalue(history.getNeedCutvalue());
                    lookpo.setStatus(history.getStatus());
                    lookpo.setPlatformCutpriceId(history.getCutpriceId());
                    lookpo.setDuration(history.getDuration());
                    lookpo.setNeedCutvalue(history.getNeedCutvalue());
                    lookpo.setCreateTime(history.getCreateTime());
                    lookpo.setCutpriceMode(history.getCutpriceMode());
                    pacakets = redPacaketsService.findById(history.getCutpriceId());
                    lookpo.setSubtitleSponser(pacakets.getSubtitleSponser());
                    lookpo.setSubtitleParticipant(pacakets.getSubtitleParticipant());
                    lookpo.setTitle(pacakets.getTitle());
                    lookpo.setAuction(pacakets.getAuction());
                    lookCutpricePos.add(lookpo);
                }
            }
        }
        //存放需要更新数据库的id
        List<Long> hisIds = new ArrayList<>();
        if (!lookCutpricePos.isEmpty()) {
            for (int l = lookCutpricePos.size() - 1; l >= 0; l--) {
                long time = 0;
                LookCutpricePo lookCutpricePo = lookCutpricePos.get(l);
                //过滤掉状态为2，但是已过期的
                if (lookCutpricePo.getStatus() == 2 && UncDate.getDateCount(Timestamp.valueOf(lookCutpricePo.getCreateTime()), new Date()) / 1000 > lookCutpricePo.getDuration()) {
                    hisIds.add(lookCutpricePo.getPlatformCutpriceHistoryId());
                    //处理数据库数据，delete redis, 为了有利于别的接口把砍价人数更新过来，暂不清空redis(只能单条执行数据库，影响性能)
                    // redisService.delete("Pl_set_" + lookCutpricePo.getPlatformCutpriceId() + "_" + lookCutpricePo.getAuction() + "_" + lookCutpricePo.getUserCutpriceId());
                    lookCutpricePos.remove(lookCutpricePo);
                }
                //状态为2的查询redis的totalReducation
                if (lookCutpricePo.getStatus() == 2) {
                    MngUserCutpricePo userCutprice = null;
                    Object object = redisService.get("Pl_set_" + lookCutpricePo.getPlatformCutpriceId() + "_" + lookCutpricePo.getAuction() + "_" + lookCutpricePo.getPlatformCutpriceHistoryId());
                    if (object != null) {
                        userCutprice = (MngUserCutpricePo) object;
                        lookCutpricePo.setTotalReducation(userCutprice.getTotalReducation());
                        //倒计时
                        time = UncDate.getDateCount(Timestamp.valueOf(lookCutpricePo.getCreateTime()), new Date()) / 1000;
                    }
                }
                //返回time
                lookCutpricePo.setTime(time);
            }
            //批量更新数据库
            if (!hisIds.isEmpty()) {
                litemallRedPacaketsHistoryService.updatePlatformCutpriceHistoryfourParties(hisIds);
            }
        }
        return lookCutpricePos;
    }


    public List<UserListPo> receivedUserList() throws Exception {
        List<UserListPo> receivedUserList = new ArrayList<>();
        List<LitemallRedPacaketsHistory> histories = litemallRedPacaketsHistoryService.getLimet20Userhistoy();
        if (histories != null) {
            UserListPo userPo = null;
            LitemallUser user = null;
            for (LitemallRedPacaketsHistory history : histories) {
                userPo = new UserListPo();
                userPo.setId(history.getId());
                userPo.setPrice(history.getPrice());
                user = litemallUserService.findUserByOpenId(history.getUserId());
                userPo.setAvatarUrl(user.getAvatar());
                userPo.setNickName(user.getNickname());
                receivedUserList.add(userPo);
            }
        }
        // List<UserListPo> bigReceivedUserList = sysPlatformCutpriceHistoryCostom.bigReceivedUserList();

        int i = 1;
        //去重
        // receivedUserList.removeAll(bigReceivedUserList);
        //在固定位置插入数据
//        for (UserListPo userListPo : bigReceivedUserList) {
//            int index = 4 * i + (i - 1);
//            if (index < receivedUserList.size()) {
//                receivedUserList.add(index, userListPo);
//            }
//            i++;
//        }
        int num = 20;
        if (receivedUserList.size() < 20) {
            num = receivedUserList.size();
        }
        List<UserListPo> receivedUsers = receivedUserList.subList(0, num);
        return receivedUsers;
    }
    /**
     * *
     *红包数量减少
     * **/
    public  int  redpacaketsCountDown(LitemallRedPacaketsHistory history,LitemallRedPacakets pacakets) throws Exception{
        List<LitemallRedPacaketsHistory>  list = litemallRedPacaketsHistoryService.findAuctionByUserId(history.getUserId(), history.getCutpriceId());
            int flag=0;
        if (list!=null&&list.size()>1) {
            logger.info("已经成功过，不减数量");
            return flag;
        }
            pacakets.setItemNum(pacakets.getItemNum()-1);
             flag = redPacaketsService.updateRedPacakets(pacakets);
            return flag;
    }
    /**
     * 砍价
     *
     * @param spfc
     * @param platformCutprice
     * @param userCutpriceId
     * @param userId
     * @return
     * @throws Exception
     */
    private int auctionBargain(LitemallRedPacaketsHistory spfc, LitemallRedPacakets platformCutprice,
                               Long userCutpriceId, String userId,SysWxConfig wxConfig) throws Exception {
        int flag = 0;
        Lock lock = new Lock("BIZ:LOCK:AUCTIONLOCK" + platformCutprice.getId(),
                "BIZ:LOCK:AUCTIONLOCK" + platformCutprice.getId());
        try {
            if (distributedLockHandler.tryLock(lock, 3000, 100)) {
                //logger.info("user get lock : " + userCutpriceId + ",now():" + System.currentTimeMillis());
                if (spfc != null && spfc.getStatus() == 2) { // 活动进行中
                    Object o = redisTemplate.boundHashOps("Pl_" + platformCutprice.getId() + "_"
                            + platformCutprice.getAuction() + "_" + userCutpriceId).get(userId);
                    Long time = redisTemplate.boundHashOps("Pl_" + platformCutprice.getId() + "_"
                            + platformCutprice.getAuction() + "_" + userCutpriceId).getExpire();
                    MngUserCutpricePo one = (MngUserCutpricePo) redisService.get("Pl_set_" + platformCutprice.getId()
                            + "_" + platformCutprice.getAuction() + "_" + userCutpriceId);
                    Object cutNum = null;
                    if (platformCutprice.getCutpriceMode() <= 3) {
                        cutNum = redisService.get("cutNum_" + userId);
                    } else {
                        cutNum = redisService.get("cutNum_" + platformCutprice.getCutpriceMode() + "_" + userId);
                    }
                    int cn = 0;
                    try {
                        if (cutNum != null) {
                            cn = (int) cutNum;
                        }
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    }
                    int integer = 0;//每日可砍次数
                    integer = this.getCuttimesdaily(platformCutprice.getCutpriceMode());
                    if (integer <= 0) {
                        integer = 99;
                    }
                    if (cn < integer) {
                        if (time >= 0 && one != null && UncDate.getDateCount(Timestamp.valueOf(spfc.getCreateTime()), new Date()) / 1000 < spfc.getDuration()) { // 2.1当活动未过期时，执行帮砍逻辑，并在status=1或抢券status=4时重置数据库信息
                            if (o == null) {// 用户没有参加过// 判断砍价是否已经完成
                                // int needCutvalue = one.getNeedCutvalue();// 需要砍价
                                int needCutvalue = one.getPrice();// 需要砍价
                                int totalReducation = one.getTotalReducation();
                                if (needCutvalue > totalReducation) {// 额度没有砍完，还可以砍
                                    LitemallUser consumer = litemallUserService.findUserByOpenId(userId);
                                    //consumerDao.findByUserId(userId);// 判断用户是否存在
                                    if (consumer != null) {

                                        Map<String, Integer> map = this.caculPrice(one, needCutvalue);
                                        int cp = map.get("cp");
                                        flag = cp;
                                        one.setParties(one.getParties() + 1);
                                        logger.info("用户昵称为:{"+consumer.getNickname()+"}；用户openid为:{"
                                                +consumer.getWeixinOpenid()+"}的用户帮助用户openid为:{ "+spfc.getUserId()
                                                +"}吧活动id为:{"+spfc.getId()+"}的活动盘了：{"+cp+"}分");
                                        int i = one.getTotalReducation() + cp;// 总砍价
                                        if (needCutvalue <= i) {// 已完成
                                            //## 完成时先处理redis数据
                                            if (needCutvalue < i) {// 这将是最后一个砍价的参与者，砍的过多，将砍价设置为差值
                                                cp = needCutvalue - one.getTotalReducation();
                                            }
                                            one.setTotalReducation(needCutvalue);
                                            if (one.getStatus() == 2) {
                                                one.setStatus(1);
                                            }
                                            logger.info("{"+spfc.getId()+"}活动已经完成");


                                            int temp = doSuccess(spfc, platformCutprice, one, userCutpriceId, needCutvalue, userId,wxConfig);
                                            //红包数量减一
                                            this.redpacaketsCountDown(spfc, platformCutprice);
                                            logger.info("temp:" + temp);
                                        } else {// 没完成
                                            one.setTotalReducation(i);
                                            one.setStatus(2);// 进行中
                                           // logger.info("redis:" + spfc.getId() + " 状态置为2");
                                        }

                                        redisTemplate.opsForHash().put("Pl_" + platformCutprice.getId() + "_" + platformCutprice.getAuction() + "_" + userCutpriceId, userId, cp);
                                        redisTemplate.expire("Pl_" + platformCutprice.getId() + "_" + platformCutprice.getAuction() + "_" + userCutpriceId, time, TimeUnit.SECONDS);
                                        redisService.setSeconds("Pl_set_" + platformCutprice.getId() + "_" + platformCutprice.getAuction() + "_" + userCutpriceId, one, 24 * 60 * 60);

                                        //此处记录用户砍的次数
                                        if (platformCutprice.getCutpriceMode() <= 3) {
                                            redisService.set("cutNum_" + userId, cn + 1, UncDate.getTimeout());
                                        } else {
                                            redisService.set("cutNum_" + platformCutprice.getCutpriceMode() + "_" + userId, cn + 1, UncDate.getTimeout());
                                        }
                                        //flag = 1;
                                        return cp;
                                    } else {
                                        // 用户不存在
                                        this.setMessage("用户不存在");
                                        flag = 0;
                                        return flag;
                                    }
                                } else {
                                    this.setMessage("用户已经完成砍价");
                                    if (spfc != null) {
                                        spfc.setTotalReducation(needCutvalue);
                                        if (one.getStatus() == 1 && spfc.getStatus() == 2) {
                                            spfc.setStatus(1);
                                            logger.info("self完成砍价:" + spfc.getId() + " 状态置为1");
                                        }
                                        spfc.setParties(one.getParties());
                                        litemallRedPacaketsHistoryService.updateStatus(spfc);
                                    }
                                    flag = 0;
                                    return flag;
                                }
                            } else {
                                int cutprice = (int) o;
                                if (cutprice == 0) {// 表示用户不可以自己砍价
                                    if (userId.equals(one.getUserId())) {
                                        this.setMessage("用户不可以自己砍价");
                                        return flag;
                                    }
                                }
                                // 用户已经参加过了
                                this.setMessage("用户已经参加过了");
                                return flag;
                            }
                        } else {
                            // 2.2砍价已经结束:当数据库status==2时 设置数据库status=3
                            if (spfc != null && spfc.getStatus() == 2) {
                                spfc.setStatus(3);
                                logger.info("self:" + spfc.getId() + " 状态置为3");
                                litemallRedPacaketsHistoryService.updateStatus(spfc);

                            }
                            this.setMessage("红包已抢完，活动被终止");
                            flag = 0;
                            return flag;
                        }
                    } else {
                        //您已经用完今天的次数
                        this.setMessage("歇一会吧，您今天盘的次数太多了");
                        flag = 0;
                        return flag;
                    }
                } else {// 券已被抢
                    flag = 0;
                    this.setMessage("红包已抢完，活动被终止");
                    return flag;
                }
            } else {
                logger.error("cannot get lock!" + userCutpriceId);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            distributedLockHandler.releaseLock(lock);
            //logger.info("releaseLock(lock) +" + System.currentTimeMillis());
        }
        return flag;
    }

    public int doSuccess(LitemallRedPacaketsHistory spfc, LitemallRedPacakets platformCutprice, MngUserCutpricePo one, Long userCutpriceId, int needCutvalue, String userId,SysWxConfig wxConfig) throws Exception {
        int flag = 0;
        //成功后竞拍券减1,处理4,5特殊操作
        Map map = couponsMinus1(spfc, platformCutprice, userCutpriceId, userId);
        logger.info("map:" + map);
        int itemNumPre = (int) map.get("itemNumPre");
        int itemNum = (int) map.get("itemNum");
        logger.info("platformCutprice.getItemNum" + platformCutprice.getItemNum());
        //当红包总数为0时
        flag = num1To2(spfc, platformCutprice, userCutpriceId, userId, itemNum, itemNumPre);
        //保存数据库
        int parties = one.getParties();
        logger.info("spfc:" + spfc);
        if (spfc != null) {
            spfc.setTotalReducation(needCutvalue);
            if (one.getStatus() == 1 && spfc.getStatus() == 2) {
                spfc.setStatus(1);
                spfc.setParties(parties);
                spfc.setFinishTime(LocalDateTime.now());
                logger.info("self:" + spfc.getId() + " 状态置为1");
                logger.info("save spfc:" + spfc);
                litemallRedPacaketsHistoryService.updateStatus(spfc);
                //发送砍价成功通知
                String formId = "";
                // if (redisService.get("formId_UIL" + one.getUserId()) != null) {
                //   formId = redisService.get("formId_UIL" + one.getUserId()).toString();
                // }
                //    if (StringUtils.isNotBlank(formId)) {
                String access_token = wxService.getAccess_token(wxConfig.getWxSubappid(),wxConfig.getWxSubappsecret());
                String bargainTemplateCode = GlobalValue.bargainTemplateCode;
                spfc.setTitle(platformCutprice.getTitle());
                if (spfc.getCutpriceMode() == 3) {

                    WechatPushOneUserUtils.newsend( spfc, null, GlobalValue.bargainTemplateCode, access_token, 3, one.getUserId());

                } else if (spfc.getCutpriceMode() == 4 || spfc.getCutpriceMode() == 5) {

                    List<String> users = (List) map.get("userIds");
                    //this.getUserIdsCanDo(platformCutprice.getId(), platformCutprice.getAuction(), spfc.getId(), spfc.getUserId(), userId);
                    logger.info("userIds:" + users.toString());
                    for (String user : users) {
                        logger.info("send tmpmsg:" + user);
                        if (redisService.get("formId_UIL_" + userCutpriceId + "_" + user) != null) {
                            formId = redisService.get("formId_UIL_" + userCutpriceId + "_" + user).toString();
                            logger.info("send tmpmsg form:" + formId);
                            if (StringUtils.isNotBlank(formId))
                                WechatPushOneUserUtils.send(formId, null, spfc, null, GlobalValue.cutpriceTemplateCode, access_token, 4, user);
                            else
                                logger.info("no form id");
                        }

                    }

                }

                //}
            }
        }
        return flag;
    }

    /**
     * @Description: num1To2
     * @param: [spfc, platformCutprice, userCutpriceId, userId, itemNum, itemNumPre]
     * @return: int
     * @auther: caiy
     * @date: 2019/7/24 0024 14:22
     */
    public int num1To2(LitemallRedPacaketsHistory spfc, LitemallRedPacakets platformCutprice, Long userCutpriceId, String userId, int itemNum, int itemNumPre) {

        int flag = 0;
        if (itemNum == 0 && itemNumPre == 1) {
            logger.info("itemNumPre:" + itemNumPre + "itemNum:" + itemNum);
            //取消置顶

            redPacaketsService.updatePlatformCutpriceTop(platformCutprice.getId(), 0);
            String prefix = "Pl_set_" + platformCutprice.getId() + "_" + platformCutprice.getAuction() + "_";
            String prefixSelf = prefix + userCutpriceId;
            List<LitemallRedPacaketsHistory> sphs = litemallRedPacaketsHistoryService
                    .findAuctionByUserId(platformCutprice.getId());
            if (sphs != null && sphs.size() > 0) {
                for (int l = sphs.size() - 1; l >= 0; l--) {
                    LitemallRedPacaketsHistory sph = sphs.get(l);
                    if (sph.getId().equals(userCutpriceId)) {
                        sphs.remove(sph);
                        if (sph.getStatus() == 4) {
                            return 0;
                        }
                    }
                }
            }
            logger.info(sphs.size() + "--sphs:" + sphs);
            if (sphs != null && sphs.size() > 0) {//
                for (LitemallRedPacaketsHistory sph : sphs) {
                    if (!sph.getId().equals(userCutpriceId)) {
                        if (!prefixSelf.equals(prefix + sph.getId())) {
                            Object object = redisService.get(prefix + sph.getId());
                            if (object != null) {
                                MngUserCutpricePo other = (MngUserCutpricePo) redisService
                                        .get(prefix + sph.getId());
                                sph.setStatus(4);
                                sph.setFinishTime(LocalDateTime.now());
                                sph.setParties(other.getParties());
                                logger.info("redisService   id:" + sph.getId() + "Status:" + sph.getStatus() + ",phParties" + sph.getParties());
                                other.setStatus(4);// 已被抢光
                                redisService.setSeconds(prefix + sph.getId(), other, 24 * 60 * 60);// 因为存放时间拿不到，再存一天
                            } else {
                                logger.error(sph.getId() + "redis 不存在");
                            }
                        }
                    } else {

                    }
                }
                logger.info("save sphs" + sphs);
                litemallRedPacaketsHistoryService.saveList(sphs);
            }
        } else if (platformCutprice.getItemNum() <= 0 && itemNumPre <= 0) {
            logger.info("itemNumPre:" + itemNumPre + "itemNum:" + itemNum);
            //取消置顶
            //platformCutprice.setTop(0);
            redPacaketsService.updatePlatformCutpriceTop(platformCutprice.getId(), 0);
            String prefix = "Pl_set_" + platformCutprice.getId() + "_"
                    + platformCutprice.getAuction() + "_";
            List<LitemallRedPacaketsHistory> sphs = litemallRedPacaketsHistoryService
                    .findAuctionByUserId(platformCutprice.getId());
            if (sphs != null && sphs.size() > 0) {//
                for (LitemallRedPacaketsHistory sph : sphs) {
                    Object object = redisService.get(prefix + sph.getId());
                    if (object != null) {
                        MngUserCutpricePo other = (MngUserCutpricePo) redisService
                                .get(prefix + sph.getId());
                        sph.setStatus(4);
                        sph.setFinishTime(LocalDateTime.now());
                        sph.setParties(other.getParties());
                        logger.info("redisService   id:" + sph.getId() + "Status:" + sph.getStatus() + ",phParties" + sph.getParties());
                        other.setStatus(4);// 已被抢光
                        redisService.setSeconds(prefix + sph.getId(), other, 24 * 60 * 60);// 因为存放时间拿不到，再存一天
                    } else {
                        logger.error(sph.getId() + "redis 不存在");
                    }
                }
                litemallRedPacaketsHistoryService.saveList(sphs);
            }
            this.setMessage("红包已被抢光，活动被终止");
            flag = 0;
        }
        return flag;
    }


    public Map couponsMinus1(LitemallRedPacaketsHistory spfc, LitemallRedPacakets platformCutprice, Long userCutpriceId, String userId) throws Exception {
        Map map = new HashMap();
        List<String> userIdsCanDo = new ArrayList<>();
        int flag = 0;
        //成功后竞拍券减1
        int itemNumPre = 0;
        int itemNum = 0;
        if (platformCutprice.getCutpriceMode() <= 3) {
            logger.info("platformCutprice.getCutpriceMode():" + platformCutprice.getCutpriceMode());
            List<LitemallRedPacaketsHistory> sps = litemallRedPacaketsHistoryService.findAuctionByUserId(spfc.getUserId(), spfc.getCutpriceId());
            if (sps != null && sps.size() >= 1) {
                logger.info("只能领取一个");
            } else if (platformCutprice.getItemNum() > 0) {
                itemNum = platformCutprice.getItemNum() - 1;
                itemNumPre = platformCutprice.getItemNum();
                logger.info("itemNumPre:" + itemNumPre + "itemNum:" + itemNum);
                redPacaketsService.updatePlatformCutpriceItemNum(platformCutprice.getId(), itemNum);
            } else {
                logger.info("红包达上限");
            }
        } else {
            logger.info("4,5platformCutprice.getCutpriceMode():" + platformCutprice.getCutpriceMode());
            itemNum = platformCutprice.getItemNum() - 1;
            itemNumPre = platformCutprice.getItemNum();
            logger.info("itemNumPre:" + itemNumPre + "itemNum:" + itemNum);
            redPacaketsService.updatePlatformCutpriceItemNum(platformCutprice.getId(), itemNum);
            //cutprice_mode=4，随机领取红包
            if (platformCutprice.getCutpriceMode() == 4) {
                userIdsCanDo = this.specialRedEnvelope(platformCutprice, spfc, userId);

            } else if (platformCutprice.getCutpriceMode() == 5) {
                List<Integer> randomPrice = new ArrayList<>();
                Map<String, Object> redPackageMap = new HashMap<>();
                // List userIdsCanDo = new ArrayList();
                userIdsCanDo = this.getUserIdsCanDo(platformCutprice.getId(), platformCutprice.getAuction(), spfc.getId(), spfc.getUserId(), userId);
                if (platformCutprice.getReceivableNum() > 0) {
                    randomPrice = APIUtil.random(platformCutprice.getReceivableNum(), platformCutprice.getPrice());
                    redPackageMap.put("receivableNum", platformCutprice.getReceivableNum());
                } else {
                    randomPrice = APIUtil.random(userIdsCanDo.size(), platformCutprice.getPrice());
                    redPackageMap.put("receivableNum", userIdsCanDo.size());
                }
                redPackageMap.put("randomPrice", randomPrice);
                logger.info("redPackageMap:" + redPackageMap);
                if (randomPrice.size() == (int) redPackageMap.get("receivableNum")) {
                    redisService.set("redPackage_" + spfc.getId(), redPackageMap, platformCutprice.getDuration() + platformCutprice.getDeadline());
                } else {
                    logger.error("redPackageMap有异常 randomPrice.size()：" + randomPrice.size() + "platformCutprice.getReceivableNum():" + platformCutprice.getReceivableNum());
                }
            }

        }
        map.put("flag", flag);
        map.put("itemNum", itemNum);
        map.put("itemNumPre", itemNumPre);
        map.put("userIds", userIdsCanDo);
        return map;
    }

    /**
     * @Description: specialRedEnvelope
     * @param: [platformCutprice, spfc]
     * @return: void
     * @auther: caiy
     * @date: 2019/7/23 0023 17:20
     */
    public List specialRedEnvelope(LitemallRedPacakets platformCutprice, LitemallRedPacaketsHistory spfc, String userid) throws Exception {
        //##获取参与人列表
        BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(
                "Pl_" + platformCutprice.getId() + "_" + platformCutprice.getAuction() + "_" + spfc.getId());
        Map<Object, Object> map = boundHashOps.entries();
        List<String> userIds = new ArrayList<>();
        if (!userid.equals(spfc.getUserId())) {
            userIds.add(userid);
        }
        if (boundHashOps != null) {
            for (Object o : map.keySet()) {
                String userId = (String) o;
                if (!spfc.getUserId().equals(userId) && StringUtils.isNotBlank(userId)) {
                    userIds.add(userId);
                }
            }
        }
        //##获取随机用户
        List<String> userIdsCanDo = new ArrayList<>();
        //发起人不可领取
        if (platformCutprice.getSelfReceivable() == 0) {
            //当同时为0时，全部人可领
            if (platformCutprice.getReceivableNum() == 0 || platformCutprice.getReceivableNum() >= platformCutprice.getMinTimes()) {
                userIdsCanDo = userIds;
                userIdsCanDo.add(spfc.getUserId());
            } else {
                userIdsCanDo = APIUtil.getRandomList(userIds, platformCutprice.getReceivableNum());
            }
        } else {
            if (platformCutprice.getReceivableNum() == 0 || platformCutprice.getReceivableNum() > platformCutprice.getMinTimes()) {
                userIdsCanDo = userIds;
            } else {
                userIdsCanDo = APIUtil.getRandomList(userIds, platformCutprice.getReceivableNum() - 1);
            }
            userIdsCanDo.add(spfc.getUserId());
        }
        //获取随机红包最终金额
        List<UserParticipant> UserParticipants = APIUtil.getRandom(userIdsCanDo, platformCutprice, spfc.getUserId());
        List<ReceiveRecord> receiveRecords = new ArrayList<>();
        //插红包库
        for (UserParticipant userParticipant : UserParticipants) {
            ReceiveRecord receiveRecord = new ReceiveRecord();
            receiveRecord.setBargainListId(spfc.getId());
            receiveRecord.setCutpriceId(platformCutprice.getId());
            receiveRecord.setFinishTime(LocalDateTime.now());
            receiveRecord.setStatus(0);
            receiveRecord.setOpenid(userParticipant.getUserId());
            receiveRecord.setPrice(userParticipant.getPrice());
            receiveRecords.add(receiveRecord);
        }
        logger.info("receiveRecords:" + receiveRecords);
        receiveRecordService.savereceive(receiveRecords);

        return userIdsCanDo;
    }


    private Map<String, Integer> caculPrice(MngUserCutpricePo one, int needCutvalue) throws Exception {
        Map<String, Integer> ll = new HashMap<String, Integer>();

        int price = one.getPrice();// 原价
        int totalReducation = one.getTotalReducation();
        int maxTimes = one.getMaxTimes();
        int minTimes = one.getMinTimes();
        int firstReduce = one.getFirstReduce();
        int parties = one.getParties();//此时砍的刀数


        int cp = 1;// 1分

        int m = 1;//砍得最小值
        double sin = 1;
        int max = 10;
        int min = 1;
        if (parties == 0) {
            sin = (int) Math.floor(price * firstReduce * 0.01);
            max = (int) (sin * (1.1));
            min = (int) (sin * (0.9));
        } else {
            //（总价-第一刀）*((1-SIN(PI()/2*刀序号/总刀数))/(总刀数*0.35))
            // int residue = price - one.getTotalReducation();//此时总剩余
            int residue = price - (int) Math.floor(price * firstReduce * 0.01);//此时总剩余
            int totalCut = (maxTimes + minTimes) / 2;
            double ii = parties * 1.0 / maxTimes;
            sin = residue * (1 - Math.sin((double) (Math.PI / 2 * ii))) / (maxTimes * 0.35);
            // int max = (int) (residue * Math.pow(sin, 5));
            max = (int) (sin * (1.1));
            min = (int) (sin * (0.9));
        }

        //算出每次的砍价边界
        int t = (price - one.getTotalReducation());//总剩余
        int a = minTimes - parties;//剩余的次数
        // int ma = (t - (m * a)) > 10 ? (t - (m * a)) : 10;//此次最大范围
        int ma = t - (m * a);//此次最大范围
        int mi = (int) Math.ceil(t * 1.0 / a);//向上取整，最小不能小于平局值
        if (max > ma) {
            max = ma;
        }
        if (min > max) {
            min = mi;
        }
        if (max < 10) {
            max = 10;
        }
        if (min < 1) {
            min = 1;
        }

        long start = System.currentTimeMillis();
        while (true) {
            cp = new Random().nextInt(Integer.valueOf(String.valueOf(max))) % (max - min + 1) + min;
            int i = (minTimes - one.getParties() - 1) * m;//最少砍的剩余总额
            int i1 = i + cp + totalReducation;//此时的总砍价额
            if (i1 <= price && cp > 0 && ((price - i1) >= m || (price - i1) == 0)) {
                break;
            }
            if ((System.currentTimeMillis() - start) > 50) {
                //判断剩余金额和最小金额的关系
                cp = 1;//
                break;
            }
        }

        if (parties + 1 >= minTimes) {
            int avg = (price - one.getTotalReducation()) / (maxTimes - parties + 1);
            if (avg > 5) {
                cp = cp + avg;
            }
        }


        //判断砍的刀数
        if (parties + 1 >= maxTimes) {//最后一刀
            cp = price - one.getTotalReducation();
        }


        int i = one.getTotalReducation() + cp;// 总砍价
        if (price <= i) {// 已完成
            if (price < i) {
                // 这将是最后一个砍价的参与者，砍的过多，将砍价设置为差值
                cp = price - one.getTotalReducation();
                if (cp < 1) {
                    cp = 1;
                }
            }
        }


        // one.setParties(parties + 1);//最新刀数
        // one.setTotalReducation(cp + one.getTotalReducation());


        // ll.put("max", max);
        // ll.put("min", min);
        ll.put("cp", cp);
        return ll;
    }


    /**
     * @Description: getCuttimesdaily
     * @param: [cutpriceMode]
     * @return: int
     * @auther: caiy
     * @date: 2019/7/24 0024 9:26
     */
    public int getCuttimesdaily(int cutpriceMode) throws Exception {
        int integer = 0;
        if (cutpriceMode != 4 && cutpriceMode != 5) {
            Object confValue = redisService.get("cutNum_cut_times_daily");
            if (confValue != null) {
                integer = (int) confValue;
            }
            if (confValue == null) {
                SysConfig sysConfig = systemConfigService.findByKey("cut_times_daily");
                String num = sysConfig.getConfValue();
                integer = Integer.parseInt(num);
            }

        } else {
            Object confValue = redisService.get("cutNum_cut_times_daily" + cutpriceMode);
            if (confValue != null) {
                integer = (int) confValue;
            }
            if (confValue == null) {
                SysConfig sysConfig = systemConfigService.findByKey("cut_times_daily" + cutpriceMode);
                confValue = sysConfig.getConfValue();
                String num = sysConfig.getConfValue();
                integer = Integer.parseInt(num);
                redisService.set("cutNum_cut_times_daily" + cutpriceMode, integer, UncDate.getTimeout());
            }
        }
        return integer;
    }

    /**
     * 红包列表
     */
    public Object list(Integer limit) {
        List<LitemallRedPacakets> redPacakets = redPacaketsService.getlist(limit,false);
        return ResponseUtil.okList(redPacakets);
    }

    /**
     * 根据活动id获取活动信息和userid
     */
    public LookCutpricePo getCutredPacaketsById(long cutRedpacaketId, String userOpenId) throws Exception {
        if (cutRedpacaketId <= 0) {
            logger.error("活动id不可为空");
            return null;
        }
        LitemallRedPacaketsHistory cutRedpacakets = litemallRedPacaketsHistoryService.getCutRedpacaketById(cutRedpacaketId);

        LitemallRedPacakets redPacakets = redPacaketsService.findById(cutRedpacakets.getCutpriceId());
        //LitemallUser  users = userService.findById(userIds);

        LookCutpricePo lookCutpricePo = new LookCutpricePo();

        if (cutRedpacakets != null && cutRedpacakets.getId() != null && redPacakets != null) {
            lookCutpricePo.setUserCutpriceId(cutRedpacakets.getId());
            lookCutpricePo.setOwner(1);
            lookCutpricePo.setTotalReducation(cutRedpacakets.getTotalReducation());
            lookCutpricePo.setNeedCutvalue(cutRedpacakets.getNeedCutvalue());
            lookCutpricePo.setUserId(cutRedpacakets.getUserId());
            lookCutpricePo.setSubtitleSponser(redPacakets.getSubtitleSponser());
            lookCutpricePo.setSubtitleParticipant(redPacakets.getSubtitleParticipant());
            lookCutpricePo.setStatus(cutRedpacakets.getStatus());
            lookCutpricePo.setPlatformCutpriceId(cutRedpacakets.getCutpriceId());
            lookCutpricePo.setPrice(cutRedpacakets.getPrice());
            lookCutpricePo.setDuration(cutRedpacakets.getDuration());
            lookCutpricePo.setActualprice(cutRedpacakets.getNeedCutvalue());
            lookCutpricePo.setPaystatus(cutRedpacakets.getPaystatus());
            lookCutpricePo.setSelfAvailable(redPacakets.getSelfAvailable());
            lookCutpricePo.setCreateTime(cutRedpacakets.getCreateTime());
            lookCutpricePo.setTitle(redPacakets.getTitle());
            lookCutpricePo.setImage(redPacakets.getImage());
            lookCutpricePo.setImage2(redPacakets.getImage2());
            lookCutpricePo.setImage3(redPacakets.getImage3());
            lookCutpricePo.setUrl(redPacakets.getUrl());
            lookCutpricePo.setUrl2(redPacakets.getUrl2());
            lookCutpricePo.setUrl3(redPacakets.getUrl3());
            lookCutpricePo.setBannerAdvertType(redPacakets.getBannerAdvertType());
            lookCutpricePo.setAdvertisingVideo(redPacakets.getAdvertisingVideo());
            lookCutpricePo.setCutpriceMode(cutRedpacakets.getCutpriceMode());
            lookCutpricePo.setAdvertisingViews(redPacakets.getAdvertisingViews());
            lookCutpricePo.setMinTimes(redPacakets.getMinTimes());
            lookCutpricePo.setAuction(redPacakets.getAuction());
            lookCutpricePo.setSelfRceivable(redPacakets.getSelfReceivable());
            lookCutpricePo.setSelfRceivable(receiveRecordService.getSelfStatus(cutRedpacakets.getId()));
        }
        //部分数据已砍刀数、是否砍过价、砍价参与人从redis中获取
        if (lookCutpricePo != null) {
            lookCutpricePo = lookRedisCutprice(lookCutpricePo);
            userOpenId = userOpenId != null ? userOpenId : lookCutpricePo.getUserId();
            lookCutpricePo = lookRedisUserListCutprice(lookCutpricePo, userOpenId);
            //获取其他数据
            lookCutpricePo = lookCutpriceOthers(lookCutpricePo, userOpenId);
        }
        return lookCutpricePo;
    }

    /**
     * @Description: lookRedisCutprice redis活动相关数据查询
     * @param: [lookCutpricePo]
     * @return: com.tmxk.diesa.po.LookCutpricePo
     * @auther: caiy
     * @date: 2019/8/1 0001 15:31
     */
    public LookCutpricePo lookRedisCutprice(LookCutpricePo lookCutpricePo) throws Exception {
        int status = lookCutpricePo.getStatus();
        Object object = redisService.get("Pl_set_" + lookCutpricePo.getPlatformCutpriceId() + "_" + lookCutpricePo.getAuction() + "_" + lookCutpricePo.getUserCutpriceId());
        MngUserCutpricePo userCutprice = null;
        if (object != null) {
            userCutprice = (MngUserCutpricePo) object;
            status = userCutprice.getStatus();
           // logger.info("测试userCutprice:" + userCutprice);
            //判断isPlay 0是未达到门限，1是达到门限
            int parties = userCutprice.getParties();
           // logger.info(userCutprice.getId() + "MinTimes-parties======AdvertisingViews" + lookCutpricePo.getMinTimes() + " " + parties + " " + lookCutpricePo.getAdvertisingViews());
            //当advertisingViews=null时，不播广告
            if (lookCutpricePo.getAdvertisingViews() != null) {
                if ((lookCutpricePo.getMinTimes() - parties) < lookCutpricePo.getAdvertisingViews()) {
                    lookCutpricePo.setIsPlay(1);
                } else {
                    lookCutpricePo.setIsPlay(0);
                }
            } else {
                lookCutpricePo.setIsPlay(0);
            }
            lookCutpricePo.setTotalReducation(userCutprice.getTotalReducation());
        }
        //判断状态
       // logger.info(lookCutpricePo.getStatus() + " status" + status + " object " + object + " " + UncDate.getDateCount(Timestamp.valueOf(lookCutpricePo.getCreateTime()), new Date()) / 1000);
        long time = 0;
        time = UncDate.getDateCount(Timestamp.valueOf(lookCutpricePo.getCreateTime()), new Date()) / 1000;
       // logger.info("time:" + time + ",duration:" + lookCutpricePo.getDuration());
        if ((lookCutpricePo.getStatus() == 2 && time > lookCutpricePo.getDuration()) || (lookCutpricePo.getStatus() == 3 && object != null)) {
            logger.info("过期置为失效");
            //过期时清除redis数据
            if (object != null) {
                litemallRedPacaketsHistoryService.updateredpacaletsHistory(lookCutpricePo.getUserCutpriceId(), 3, userCutprice.getParties(), userCutprice.getTotalReducation());
                redisService.delete("Pl_set_" + lookCutpricePo.getPlatformCutpriceId() + "_" + lookCutpricePo.getAuction() + "_" + lookCutpricePo.getUserCutpriceId());
            } else {
                litemallRedPacaketsHistoryService.updateRedpacaket(lookCutpricePo.getUserCutpriceId(), 3);
            }
            lookCutpricePo.setStatus(3);
        }
        //返回time
        if (lookCutpricePo.getStatus() == 2) {
           // logger.info("2 time:" + time);
            lookCutpricePo.setTime(time);
        } else {
            lookCutpricePo.setTime(0);
        }
        return lookCutpricePo;
    }

    /**
     * @Description: lookRedisUserListCutprice redis中砍价人员相关
     * @param: [lookCutpricePo, userid]
     * @return: com.tmxk.diesa.po.LookCutpricePo
     * @auther: caiy
     * @date: 2019/8/1 0001 15:30
     */
    public LookCutpricePo lookRedisUserListCutprice(LookCutpricePo lookCutpricePo, String userid) throws Exception {

        List<ConsumerPo> consumerList = new ArrayList<>();
        int isCutprice = 0;
        BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(
                "Pl_" + lookCutpricePo.getPlatformCutpriceId() + "_" + lookCutpricePo.getAuction() + "_" + lookCutpricePo.getUserCutpriceId());
        Map<Object, Object> map = boundHashOps.entries();
        if (boundHashOps != null) {
            for (Object o : map.keySet()) {
                try {
                    String userId = (String) o;
                    if (userid.equals(userId)) {
                        isCutprice = 1;
                    }
                    int cutprice = (int) map.get(o);
                    if (cutprice != 0) {
                        ConsumerPo consumerPo = new ConsumerPo();
                        if (StringUtils.isNotBlank(userId)) {
                            LitemallUser consumer = userService.findUserByOpenId(userId);

                            if (consumer != null) {
                                consumerPo.setUserId(userId);
                                consumerPo.setGender(consumer.getGender());
                                consumerPo.setNickName(consumer.getNickname());
                                consumerPo.setAvatarUrl(consumer.getAvatar());
                                consumerPo.setCutprice(cutprice);
                                consumerList.add(consumerPo);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                    this.setMessage("数据异常");
                    return null;
                }
            }
        }
        //logger.info("consumerList:" + consumerList);
        //返回参与人
        lookCutpricePo.setConsumerList(consumerList);
        //返回是否已砍价
        lookCutpricePo.setIsCutprice(isCutprice);
        return lookCutpricePo;
    }

    /**
     * @Description: lookCutpriceOthers 查询与砍价动作无关的其他数据
     * @param: [lookCutpricePo, userid]
     * @return: com.tmxk.diesa.po.LookCutpricePo
     * @auther: yica
     * @date: 2019/8/1 0001 15:27
     */
    public LookCutpricePo lookCutpriceOthers(LookCutpricePo lookCutpricePo, String userid) throws Exception {
        //images
        List<ActivityImage> activityImages = new ArrayList<>();
        if (StringUtils.isNotBlank(lookCutpricePo.getImage()) || StringUtils.isNotBlank(lookCutpricePo.getUrl())) {
            ActivityImage activityImage = new ActivityImage();
            activityImage.setImage(lookCutpricePo.getImage());
            if (StringUtils.isNotBlank(lookCutpricePo.getUrl())) {
                activityImage.setUrl(lookCutpricePo.getUrl());
            } else {
                activityImage.setUrl("");
            }
            activityImage.setDefaut(1);
            activityImages.add(activityImage);
        }
        if (StringUtils.isNotBlank(lookCutpricePo.getImage2()) || StringUtils.isNotBlank(lookCutpricePo.getUrl2())) {
            ActivityImage activityImage = new ActivityImage();
            activityImage.setImage(lookCutpricePo.getImage2());
            if (StringUtils.isNotBlank(lookCutpricePo.getUrl2())) {
                activityImage.setUrl(lookCutpricePo.getUrl2());
            } else {
                activityImage.setUrl("");
            }
            activityImages.add(activityImage);
        }
        if (StringUtils.isNotBlank(lookCutpricePo.getImage3()) || StringUtils.isNotBlank(lookCutpricePo.getUrl3())) {
            ActivityImage activityImage = new ActivityImage();
            activityImage.setImage(lookCutpricePo.getImage3());
            if (StringUtils.isNotBlank(lookCutpricePo.getUrl3())) {
                activityImage.setUrl(lookCutpricePo.getUrl3());
            } else {
                activityImage.setUrl("");
            }
            activityImages.add(activityImage);
        }
        lookCutpricePo.setActivityImages(activityImages);
        //返回可领取人员列表
       // List<String> receivableUserIds = new ArrayList<>();
        if (lookCutpricePo.getCutpriceMode() == 4 && (lookCutpricePo.getStatus() == 1 || lookCutpricePo.getStatus() == 0)) {
            lookCutpricePo.setReceivableUserIds(getReceivableUserIds(lookCutpricePo.getUserCutpriceId()));
        } else if (lookCutpricePo.getCutpriceMode() == 5 && (lookCutpricePo.getStatus() == 1 || lookCutpricePo.getStatus() == 0)) {
            lookCutpricePo.setReceivableUserIds(this.getUserIdsCanDo(lookCutpricePo.getPlatformCutpriceId(), lookCutpricePo.getAuction(), lookCutpricePo.getUserCutpriceId(), lookCutpricePo.getUserId(), ""));
        }
        //返回articles
        lookCutpricePo.setArticles(getUrl());
        //返回userList
        //List<UserListPo> receivedUserList = new ArrayList<>();
        //receivedUserList = receivedUserList();
        //lookCutpricePo.setUserList(receivedUserList);
        //是否是发起者本人
        if (userid.equals(lookCutpricePo.getUserId())) {
            lookCutpricePo.setIsSelf(1);
        } else {
            lookCutpricePo.setIsSelf(0);
        }
        return lookCutpricePo;
    }

    public List<String> getReceivableUserIds(Long id) throws Exception {
        List<String> receivableUserIds = new ArrayList<>();
        List<ReceiveRecord> receiveRecords = receiveRecordService.findreceiveRecordByListIdAndstatus(id, 0);

        if (receiveRecords != null && receiveRecords.size() > 0) {
            for (ReceiveRecord receiveRecord : receiveRecords) {
                receivableUserIds.add(receiveRecord.getOpenid());
            }
        }
        return receivableUserIds;


    }

    public Articles getUrl() throws Exception {
        Long id = 0l;
        Object confValue = redisService.get("articles_id");
        if (confValue != null) {
            id = (long) confValue;
        } else {
            SysConfig config = systemConfigService.findByKey("articles_id");

            if (config != null) {
                String confVal = config.getConfValue();
                id = Long.valueOf(confVal);
                redisService.set("articles_id", id, UncDate.getTimeout());
            }
        }
        Articles articles = articlesService.findOne(id);
        return articles;
    }

    /**
     * @Description: getUserIdsCanDo 获取活动所有人
     * @param: [platformCutprice, spfc, userid]
     * @return: java.util.List
     * @auther: caiy
     * @date: 2019/7/25 0025 16:04
     */
    public List<String> getUserIdsCanDo(long platformCutpriceId, int auction, long hisId, String hisUserId, String userid) throws Exception {
        //##获取参与人列表
        BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(
                "Pl_" + platformCutpriceId + "_" + auction + "_" + hisId);
        Map<Object, Object> map = boundHashOps.entries();
        List<String> userIds = new ArrayList<>();
        if (StringUtils.isNotBlank(userid) && !userid.equals(hisUserId)) {
            userIds.add(userid);
        }
        if (boundHashOps != null) {
            for (Object o : map.keySet()) {
                String userId = (String) o;
                if (!hisUserId.equals(userId) && StringUtils.isNotBlank(userId)) {
                    userIds.add(userId);
                }
            }
        }
        //##获取随机用户
        List<String> userIdsCanDo = new ArrayList<>();
        userIdsCanDo = userIds;
        userIdsCanDo.add(hisUserId);
        logger.info("userIdsCanDo:" + userIdsCanDo);
        return userIdsCanDo;
    }

    public LitemallRedPacaketsHistory platformCutpriceBargain(SysPlatformCutpriceHistoryMap cutprice, String formId) throws Exception {
        SysWxConfig wxConfig = systemWxConfigService.getconfigByAppletNam(cutprice.getAppletName());

        // LitemallUser user = userService.findById(userId);
        // cutprice.setUserId(user.getWeixinOpenid());
      //  LitemallRedPacakets redPacakets = redPacaketsService.findById(cutprice.getCutpriceId());
       // int flag = 0;
        LitemallRedPacakets platformCutprice = redPacaketsService.findById(cutprice.getCutpriceId());
    /*List<SysPlatformCutpriceHistory> pfch = null;
    if (platformCutprice.getAuction() == 1) {
      logger.info("platformCutprice.getTop():" + platformCutprice.getTop() + "，System.currentTimeMillis()："
        + System.currentTimeMillis());
      pfch = platformCutpriceHistoryDao.findByUserId(cutprice.getUserId());
    }*/
        if (platformCutprice != null && platformCutprice.getStatus() == 1 && platformCutprice.getCutpriceMode() != 6
                &&  platformCutprice.getItemNum() > 0 ) {// 平台砍价活动有效
            //UncDate.getDateCount(platformCutprice.getEndTime(), LocalDate.now()) < 0 &&
            //&& UncDate.getDateCount(platformCutprice.getStartTime(), LocalDate.now()) >= 0

            // 1.新增用户发起活动记录
            LitemallRedPacaketsHistory platformCutpriceHistory = new LitemallRedPacaketsHistory();
            platformCutpriceHistory.setBatchId(platformCutprice.getBatchId());
            platformCutpriceHistory.setCreateTime(LocalDateTime.now());
            platformCutpriceHistory.setCutpriceId(cutprice.getCutpriceId());
            platformCutpriceHistory.setNeedCutvalue(platformCutprice.getPrice() - platformCutprice.getTarget());
            platformCutpriceHistory.setParties(0);
            platformCutpriceHistory.setStatus(2);// 进行中
            platformCutpriceHistory.setTotalReducation(0);
            platformCutpriceHistory.setCutpriceMode(platformCutprice.getCutpriceMode());
            platformCutpriceHistory.setUserId(cutprice.getWopenId());
            platformCutpriceHistory.setTradeNo(getTradeNo());
            platformCutpriceHistory.setWxConfigId(platformCutprice.getWxConfigId());
            platformCutpriceHistory.setMinPerreduce(platformCutprice.getMinPerreduce());

            platformCutpriceHistory.setPartnerTradeNo(getPartnerTradeNo(wxConfig.getWxSubmchid()));

            platformCutpriceHistory.setSubtitleParticipant(platformCutprice.getSubtitleParticipant());
            // platformCutpriceHistory.setMinPerreduce(platformCutprice.getMinPerreduce());
            // platformCutpriceHistory.setMaxPerreduce(platformCutprice.getMaxPerreduce());
            platformCutpriceHistory.setPrice(platformCutprice.getPrice());
            platformCutpriceHistory.setDuration(platformCutprice.getDuration());
            platformCutpriceHistory.setPaystatus(0);
            //String partnerTradeNo = getPartnerTradeNo(mch_id);
            platformCutpriceHistory.setMaxPerreduce(platformCutprice.getMaxPerreduce());
            //logger.info(""+cutprice.);
            LitemallRedPacaketsHistory spfch = litemallRedPacaketsHistoryService.saveAndreturn(platformCutpriceHistory);

            redisService.set("formId_UIL" + cutprice.getWopenId(), formId, spfch.getDuration());
            // 将砍价好友列表存入redis，自已可砍时userId默认不计其中，砍完记录，否则默认记录
            if (platformCutprice.getSelfAvailable() == 0) {// 自己参与砍价：0可以，1不可以
                redisTemplate.opsForHash().put(
                        "Pl_" + platformCutprice.getId() + "_" + platformCutprice.getAuction() + "_" + spfch.getId(),
                        "", 0);
            } else {
                redisTemplate.opsForHash().put(
                        "Pl_" + platformCutprice.getId() + "_" + platformCutprice.getAuction() + "_" + spfch.getId(),
                        cutprice.getWopenId(), 0);
            }
            // redis时间设置为活动持续时间
            redisTemplate.expire(
                    "Pl_" + platformCutprice.getId() + "_" + platformCutprice.getAuction() + "_" + spfch.getId(),
                    platformCutprice.getDuration() + platformCutprice.getDeadline(), TimeUnit.SECONDS);

            // 组装数据存入redis,时间为一天
            MngUserCutpricePo userCutpricePo = new MngUserCutpricePo();
            BeanUtils.copyProperties(spfch, userCutpricePo);
            // userCutpricePo.setMin((int) Math.floor(platformCutprice.getMaxPerreduce() * 0.8));//可变的最小砍价金额,起始值为高价的0.8，向下取整
            //userCutpricePo.setMin((platformCutprice.getMaxPerreduce() + spfch.getMinPerreduce()) / 2);// 可变的最小砍价金额,起始值为高价和低价的中间值
            userCutpricePo.setSelfAvailable(platformCutprice.getSelfAvailable());
            userCutpricePo.setAuction(platformCutprice.getAuction());
            userCutpricePo.setTitle(platformCutprice.getTitle());

            //存入总金额需要计算
            int price = platformCutprice.getPrice();
            userCutpricePo.setPrice((int) (price - Math.floor(price * platformCutprice.getTarget() * 0.01)));
            //存入最少砍价的次数
            userCutpricePo.setMinTimes(platformCutprice.getMinTimes());
            userCutpricePo.setMaxTimes(platformCutprice.getMaxTimes());
            userCutpricePo.setFirstReduce(platformCutprice.getFirstReduce());

            //广告播放次数门限，剩余最小砍价次数小于此值时，每次砍价强制用户看广告
            userCutpricePo.setAdvertisingViews(platformCutprice.getAdvertisingViews());
            //查询发起人关联信息，存redis
            LitemallUser sysConsumer = litemallUserService.queryByOid(spfch.getUserId());

            if (sysConsumer != null) {
                userCutpricePo.setNickName(sysConsumer.getNickname());
                userCutpricePo.setAvatarUrl(sysConsumer.getAvatar());
                logger.info("发起记录用户:{"+sysConsumer.getNickname()+"}发起了cutpriceId为:{"+platformCutprice.getId()+"}的盘红包活动");
            }
            String key = "Pl_set_" + platformCutprice.getId() + "_" + platformCutprice.getAuction() + "_"
                    + spfch.getId();
            redisService.setSeconds(
                    "Pl_set_" + platformCutprice.getId() + "_" + platformCutprice.getAuction() + "_" + spfch.getId(),
                    userCutpricePo, 24 * 60 * 60);
            //logger.info(key);
            int flag = 1;
            //spfch.set
            spfch.setTitle(platformCutprice.getTitle());
            return spfch;
        }
        return null;
    }


    public String getTradeNo() {
        String code = "";
        for (int i = 0; i < 8; i++) {
            code += (int) (Math.random() * 9);
        }
        String today = new SimpleDateFormat("MMddHHmmssSSS").format(new Date());
        String out_trade_no = code + today;//
        return out_trade_no;
    }

    private String getPartnerTradeNo(String wxSubmchid) {
        String code = "";
        for (int i = 0; i < 8; i++) {
            code += (int) (Math.random() * 9);
        }
        String today = new SimpleDateFormat("MMddHHmmssSSS").format(new Date());
        String partnerTradeNo = wxSubmchid + today + code;//
        return partnerTradeNo;
    }
//    public List<UserListPo> receivedUserList() throws Exception {
//        List<UserListPo> receivedUserList = sysPlatformCutpriceHistoryCostom.ReceivedUserList();
//        List<UserListPo> bigReceivedUserList = sysPlatformCutpriceHistoryCostom.bigReceivedUserList();
//        int i = 1;
//        //去重
//        receivedUserList.removeAll(bigReceivedUserList);
//        //在固定位置插入数据
//        for (UserListPo userListPo : bigReceivedUserList) {
//            int index = 4 * i + (i - 1);
//            if (index < receivedUserList.size()) {
//                receivedUserList.add(index, userListPo);
//            }
//            i++;
//        }
//        int num = 20;
//        if (receivedUserList.size() < 20) {
//            num = receivedUserList.size();
//        }
//        List<UserListPo> receivedUsers = receivedUserList.subList(0, num);
//        return receivedUsers;
//    }

}